package com.qianfeng.smartdevices.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartdevices.event.ColorCommandEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class ColorCommandHandler extends TextWebSocketHandler {
    private Map<Object, WebSocketSession> allClients = new HashMap<>();

    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        Object name = session.getAttributes().get("name");
        System.err.println("颜色建立websocket请求了==>"+name);
        allClients.put(name,session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        System.err.println("收到颜色发来的消息" + message.getPayload());


    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
    @EventListener
    @Async
    public void onEvent(ColorCommandEvent event) throws IOException {
        System.err.println(Thread.currentThread().getName());
        String uuid = event.getUuid();
        WebSocketSession socketSession = allClients.get(uuid);
        if (socketSession != null && socketSession.isOpen()) {
            socketSession.sendMessage(new TextMessage(event.getCommand()));
        }
    }
}
